package com.syncomponents.xml.convert;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;


/**
 * 日期转换
 * 
 * @author sunkey
 * @date Jul 18, 2014
 */
public class JavaUtilDateConverter implements Converter {
    private Locale locale = Locale.SIMPLIFIED_CHINESE;
    
    public JavaUtilDateConverter() {
    }

    public JavaUtilDateConverter(Locale locale) {
        super();
        this.locale = locale;
    }

    @SuppressWarnings("rawtypes")
    public boolean canConvert(Class clazz) {
        return Calendar.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        Calendar calendar = (Calendar) value;
        Date date = calendar.getTime();
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", this.locale);
        writer.setValue(formatter.format(date));
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        GregorianCalendar calendar = new GregorianCalendar();
        // 时间本地化
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", this.locale);
        try {
            calendar.setTime(formatter.parse(reader.getValue()));
        } catch (ParseException e) {
            throw new ConversionException(e.getMessage(), e);
        }
        return calendar;
    }
}